package com.demo2do.mobile.web.controller.authority;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.handler.CookieHandler;
import com.demo2do.mobile.Constant;
import com.demo2do.mobile.handler.AutoLoginHandler;

/**
 * 
 * @author mohanlan
 *
 */
@Controller()
@RequestMapping("/auto-login")
public class AutoLoginController {
    
    private static final Logger logger = LoggerFactory.getLogger(AutoLoginController.class);
    
    @Autowired
    private AutoLoginHandler autoLoginHandler;
    
    @Autowired
    private CookieHandler cookieHandler;
    
    /**
     * Auto login view
     * 
     * @param uuid
     * @param response
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String autoLogin(@RequestParam("uuid") String uuid,
                            HttpServletResponse response) {
        
        logger.info("#autoLogin() get request param uuid [{}]", uuid);
        
        HttpResult httpResult = autoLoginHandler.getUserInfo(uuid);
        
        if(!httpResult.isValid()) {
            return "redirect:/auto-login/error";
        }
        
        logger.info("#autoLogin() get http result [{}], responseText[{}]", JsonUtils.toJson(httpResult), httpResult.getResponseText());
        
        HttpResult userInfoResult = JsonUtils.parse(httpResult.getResponseText(), HttpResult.class);
        
        Map<String, Object> params = userInfoResult.getData();
        
        if(!params.containsKey("web_auth")) {
            return "redirect:/auto-login/error";
        }
        
        Map<String, Object> webAuth = (Map<String, Object>) params.get("web_auth");
        
        String openid = webAuth.get("openid").toString();
        String redirectUrl = webAuth.get("redirect_url").toString();
        
        logger.info("#autoLogin() add openid into cookie name[{}] value[{}] ", Constant.OPENID_KEY, openid);
        cookieHandler.addCookie(response, Constant.OPENID_KEY, openid, Constant.OPENID_EXPIRE_TIME);
        
        
        if(webAuth.containsKey("account")) {
            
        	logger.info("#autoLogin() the wechatAccount is [{}]", webAuth.get("account"));
        	
        	Map<String, Object> accountParams = JsonUtils.parse(JsonUtils.toJson(webAuth.get("account")));
        	
        	if(accountParams.size() > 0) {
        		
        		String time = String.valueOf(new Date().getTime());
        		
                logger.info("#autoLogin() add user account into cookie name[{}] value[{}] ", Constant.USER_ACCOUNT_KEY, "test-account-id:" + time);
                
                cookieHandler.addCookie(response, Constant.USER_ACCOUNT_KEY, "test-account-id:" + time, Constant.OPENID_EXPIRE_TIME);
        	}
        }
        
        return "redirect:" + redirectUrl;
    }
    
    /**
     * @return
     */
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error() {
        return "auth/auth-error";
    }
}
